import 'dart:io';

import 'package:flutter/material.dart';
import 'package:my_app/common/common.dart';
import 'package:my_app/qr_detail/qr_detail.dart';
import 'package:my_app/service/api/api.dart';
import 'package:path_provider/path_provider.dart';

class QrList extends StatefulWidget {
  QrList({Key? key, required this.batchNumbe}) : super(key: key);
  final String batchNumbe;
  @override
  State<QrList> createState() => _QrListState(batchNumbe: this.batchNumbe);
}

class _QrListState extends State<QrList> {
  late final String batchNumbe;
  _QrListState({required this.batchNumbe});
  // button 文字样式
  TextStyle _buttonTextStyle = TextStyle(
    fontSize: 10.0,
    color: Colors.white,
  );
  // button 样式
  ButtonStyle _buttonStyle = TextButton.styleFrom(
    backgroundColor: Color(Common.muji),
    padding: EdgeInsets.all(5),
  );
  //label 字体大小
  TextStyle textStyle = TextStyle(fontSize: 10);
  // label 文字对齐方式
  TextAlign textStyleAlign = TextAlign.end;

  String _qrCode = ""; // 二维码
  String _goodsCode = ""; // 商品条码
  // 效期选择值
  int? _status;

  double paddingLeft = 45.0;
  double itemWidth = 100.0;
  // listView 滚动
  ScrollController _scrollController = ScrollController();

  String startNum = '1';
  String endNum = '200';
  TextEditingController _qrcontroller = new TextEditingController();
  List listData = [
    // {
    //   "ITEM_ID": "2701030000272",
    //   "QR_ID": "QRZB000022032401060000100016",
    //   "END_DT": "2022-04-23",
    //   "QR_FLG": "赋码完成"
    // }
  ];
  @override
  initState() {
    getListData(batchNumbe);
    super.initState();
    // Map userinfo = {"userName":"张三","age":20};
  }

  double getFromWidth() {
    MediaQueryData mq;
    mq = MediaQuery.of(context);
    // 设备宽度
    double deviceWidth = mq.size.width;
    double width = 210;
    if (deviceWidth > 360) {
      width = 130;
    } else {
      width = mq.size.width - 80;
    }
    return width;
  }

  double getWidth() {
    MediaQueryData mq;
    mq = MediaQuery.of(context);
    // 设备宽度
    double deviceWidth = mq.size.width;
    double width = 210; // 列表内容大小
    if (deviceWidth > 360) {
      width = 180;
    } else {
      width = 133;
    }
    return width;
  }

  double getfontSize() {
    MediaQueryData mq;
    mq = MediaQuery.of(context);
    // 设备宽度
    double deviceWidth = mq.size.width;
    double fontSize = 11; // 列表内容大小
    if (deviceWidth > 360) {
      fontSize = 10;
    } else {
      fontSize = 8;
    }
    return fontSize;
  }

  void getListData(String ifsn,
      [String qrCode = '', String goodsCode = '', String status = '']) async {
    var data = await ApiService.nowQrListData(
        ifsn, startNum, endNum, qrCode, goodsCode, '', '', '', status);
    print(
        "_________________________________________listData__________________________");
    print(data);
    try {
      if (data != null) {
        listData = data;
        print("_________________________listData");
        print(listData);
        setState(() {
          listData = data;
        });
      }
    } catch (err) {
      Future.delayed(Duration(milliseconds: 5000), () {
        Common.showTost(err.toString());
      });
    }
  }

  ///getExternalStorageDirectory()：获取存储卡目录，仅支持Android；
  /// 找到正确的本地路径
  /// getApplicationDocumentsDirectory 类似iOS的NSDocumentDirectory和Android上的AppData目录
  get localDocPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

  /// getTemporaryDirectory 类似iOS的NSTemporaryDirectory和Android的getCacheDir
  get localTempPath async {
    final directory = await getTemporaryDirectory();
    return directory.path;
  }

  ///创建文件夹
  setFileFolder(String path) async {
    Directory directory = new Directory('$path');
    if (!directory.existsSync()) {
      directory.createSync();
      debugPrint('文件夹初始化成功，文件保存路径为 ${directory.path}');
    } else {
      debugPrint('文件夹已存在');
    }
    return directory.path;
  }

  ///创建文件
  setFile(String path) {
    File file = new File('$path');
    if (!file.existsSync()) {
      file.createSync();
      debugPrint('创建成功');
    } else {
      debugPrint('文件已存在');
    }
    return file;
  }

  /// 将数据写入文件
  void writeCounter(String path, String content) async {
    // Write the file
    File file = await setFile(path);
    try {
      file.writeAsStringSync('$content');
      debugPrint('文件写入成功');
    } catch (e) {
      debugPrint('文件写入失败');
    }
  }

  /// 从文件中读取数据
  readCounter(String path) async {
    File file = await setFile(path);
    try {
      // Read the file
      String contents = file.readAsStringSync();
      debugPrint('文件读取成功:$contents');
      return contents;
    } catch (e) {
      debugPrint('文件读取失败');
      return '';
    }
  }

  ///文件/文件夹删除
  deleteFilefloder(String path) {
    Directory directory = new Directory(path);
    if (directory.existsSync()) {
      List<FileSystemEntity> files = directory.listSync();
      if (files.length > 0) {
        files.forEach((file) {
          file.deleteSync();
        });
      }
      directory.deleteSync();
      debugPrint('文件夹删除成功');
    }
  }

  ///删除文件
  deleteFile(String path) {
    File file = new File('$path');
    if (file.existsSync()) {
      try {
        file.deleteSync();
        debugPrint('文件删除成功');
      } catch (e) {
        debugPrint('文件删除失败');
      }
    }
  }

  ///遍历所有文件
  getAllSubFile(String path) async {
    Directory directory = new Directory(path);
    if (directory.existsSync()) {
      return directory.listSync();
    }
    return [];
  }

  /// 获取文档目录
  Future<String> _localfilePath() async {
    Directory tempDir = await getApplicationSupportDirectory();
    return tempDir.path;
  }

  /// 获取文档
  Future<File> _localfile() async {
    String path = await _localfilePath();
    Common.showTost('文件保存目录:$path/data.json');
    return new File('$path/data.json');
  }

  /// 保存内容到文本
  void _saveFile(String val) async {
    try {
      File file = await _localfile();
      IOSink sink = file.openWrite(mode: FileMode.append);
      sink.write(val);
      sink.close();
    } catch (e) {
      // 写入错误
      print(e);
    }
  }

  // 文件下载
  void downFile() {
    _saveFile(listData.toString());
  }

  // 渲染list widget
  List<Widget> _getListData() {
    List<Widget> listdd = [];
    for (var i = 0; i < this.listData.length; i++) {
      listdd.add(
        Container(
          height: 30,
          child: InkWell(
            onTap: () {
              print("QR_ID");
              Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                // return QrDetail(listData: this.listData[i]);
                return QrDetail(
                  qrCode: this.listData[i]["QR_ID"],
                  isEdit: this.listData[i]["QR_FLG"],
                );
              })).then((value) => {
                    print(".then(onGoBack)"),
                    getListData(batchNumbe),
                  });
            },
            child: Row(
              // textBaseline: TextBaseline.ideographic,
              // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Expanded(
                  flex: 5,
                  child: Container(
                    height: 14,
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(width: 0.3, color: Colors.black),
                      ),
                    ),
                    width: itemWidth,
                    child: Row(
                      children: [
                        Text(
                          this.listData[i]["QR_ID"],
                          style: TextStyle(fontSize: getfontSize()),
                        ),
                      ],
                    ),
                  ),
                ),
                Expanded(
                  flex: 2,
                  child: Container(
                    height: 14,
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(width: 0.3, color: Colors.black),
                      ),
                    ),
                    width: itemWidth,
                    child: Row(
                      children: [
                        Text(
                          this.listData[i]["ITEM_ID"],
                          style: TextStyle(fontSize: getfontSize()),
                        ),
                      ],
                    ),
                  ),
                ),
                Expanded(
                  flex: 2,
                  child: Container(
                    height: 14,
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(width: 0.3, color: Colors.black),
                      ),
                    ),
                    width: itemWidth,
                    child: Row(
                      children: [
                        Text(
                          this.listData[i]["END_DT"],
                          style: TextStyle(fontSize: getfontSize()),
                        ),
                      ],
                    ),
                  ),
                ),

                Expanded(
                  flex: 1,
                  child: Container(
                    height: 14,
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(width: 0.3, color: Colors.black),
                      ),
                    ),
                    width: itemWidth,
                    child: Row(
                      children: [
                        Text(
                          this.listData[i]["QR_FLG"],
                          style: TextStyle(fontSize: getfontSize()),
                        ),
                      ],
                    ),
                  ),
                ),
                SizedBox(width: 10),
                // Text("______"),
                // Text(this.listData[i]["goodsCode"]),
              ],
            ),
          ),
        ),
      );
    }
    return listdd;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('二维码赋码详情'),
        centerTitle: true,
        backgroundColor: Color(Common.muji),
        leading: IconButton(
          tooltip: '返回',
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
        // actions: [
        //   IconButton(
        //     tooltip: '返回',
        //     icon: const Icon(Icons.arrow_downward),
        //     onPressed: () {
        //       downFile();
        //     },
        //   ),
        // ],
      ),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Color(Common.muji),
        child: Icon(
          Icons.arrow_upward,
          color: Colors.white,
          size: 40,
        ),
        onPressed: () {
          _scrollController.jumpTo(0.0);
        },
      ),
      body: Padding(
        padding: EdgeInsets.fromLTRB(10, 30, 0, 0),
        child: Column(
          children: [
            Wrap(
              spacing: 2, //主轴上子控件的间距
              runSpacing: 5, //交叉轴上子控件之间的间距
              children: [
                Container(
                  width: 50,
                  child: Text(
                    "二维码:",
                    style: TextStyle(fontSize: 11),
                    textAlign: textStyleAlign,
                  ),
                ),
                Container(
                  height: 30,
                  width: getFromWidth(),
                  child: TextField(
                    onChanged: (value) {
                      _qrCode = value;
                      print(_qrCode);
                    },
                    controller: _qrcontroller,
                    onSubmitted: (value) {
                      // Uri u = Uri.parse(value);
                      // value = u.queryParameters['qrCode'].toString();
                      if (value.indexOf("=") > -1) {
                        value = value.split("=")[1];
                      }
                      _qrcontroller.text = value;
                      // _qrfocusNode.unfocus();
                      // FocusScope.of(context).requestFocus(_goodsfocusNode);
                      // 保存qr码
                      setState(() {
                        _qrCode = value;
                      });
                    },
                    decoration: InputDecoration(
                      border: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.black, width: 2.0),
                      ),
                      focusedBorder: Common.focusedBorder,
                    ),
                  ),
                ),
                Container(
                  width: 50,
                  child: Text(
                    "商品条码:",
                    style: TextStyle(fontSize: 11),
                    textAlign: textStyleAlign,
                  ),
                ),
                Container(
                  height: 30,
                  width: getFromWidth(),
                  // color: Colors.amber,
                  // decoration: sty(

                  // ),
                  child: TextField(
                    onChanged: (value) {
                      _goodsCode = value;
                    },
                    decoration: InputDecoration(
                      border: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.black, width: 2.0),
                      ),
                      focusedBorder: Common.focusedBorder,
                    ),
                  ),
                ),
                Container(
                  width: 50,
                  child: Text(
                    "状态:",
                    style: TextStyle(fontSize: 11),
                    textAlign: textStyleAlign,
                  ),
                ),
                Container(
                  height: 30,
                  width: getFromWidth(),
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.black38, width: 1),
                    borderRadius: BorderRadius.vertical(
                      top: Radius.elliptical(4, 4),
                      bottom: Radius.elliptical(4, 4),
                    ),
                  ),
                  child: DropdownButton(
                      value: _status,
                      icon: Icon(Icons.arrow_drop_down),
                      iconSize: 20,
                      iconEnabledColor: Colors.black.withOpacity(0.7),
                      hint: Text('请选择'),
                      style: TextStyle(color: Colors.black, fontSize: 11),
                      isExpanded: true,
                      underline: Container(color: Colors.white),
                      items: [
                        DropdownMenuItem(
                            child: Row(children: <Widget>[
                              Text('已赋码 '),
                              SizedBox(width: 10),
                              // Icon(Icons.ac_unit)
                            ]),
                            value: 1),
                        DropdownMenuItem(
                            child: Row(children: <Widget>[
                              Text('未赋码'),
                              SizedBox(width: 10),
                              // Icon(Icons.ac_unit)
                            ]),
                            value: 2),
                      ],
                      onChanged: (value) {
                        setState(() => _status = value as int?);

                        print(value);
                      }),
                ),
              ],
            ),
            SizedBox(height: 10),
            Row(
              children: [
                Container(
                  width: 60,
                  height: 30,
                  child: TextButton(
                    style: _buttonStyle,
                    child: Text(
                      "查询",
                      style: _buttonTextStyle,
                    ),
                    onPressed: () => {
                      if (_status != null)
                        {
                          getListData(batchNumbe, _qrCode, _goodsCode,
                              _status.toString()),
                          print('$_qrCode-$_goodsCode-$_status')
                        }
                      else
                        {
                          getListData(batchNumbe, _qrCode, _goodsCode, ""),
                        }
                      // getListData(batchNumbe, _qrCode, _goodsCode, _status),
                      // print('$_qrCode-$_goodsCode-$_status')
                    },
                  ),
                ),
              ],
            ),
            SizedBox(height: 20),
            Container(
              height: 20,
              child: Row(
                // textBaseline: TextBaseline.ideographic,
                // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                // mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Expanded(
                    flex: 5,
                    child: Container(
                      width: itemWidth,
                      child: Row(
                        children: [
                          Text(
                            "二维码",
                            style: TextStyle(fontSize: 10),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 2,
                    child: Container(
                      width: itemWidth,
                      child: Row(
                        children: [
                          Text(
                            "商品条码",
                            style: TextStyle(fontSize: 10),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 2,
                    child: Container(
                      width: itemWidth,
                      child: Row(
                        children: [
                          Text(
                            "到期日期",
                            style: TextStyle(fontSize: 10),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 1,
                    child: Container(
                      width: itemWidth,
                      child: Row(
                        children: [
                          Text(
                            "状态",
                            style: TextStyle(fontSize: 10),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: Container(
                height: 100,
                // color: Colors.red,
                child: ListView(
                  controller: _scrollController,
                  children: this._getListData(),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
